package com.atguigu.srb.core.config;


import com.atguigu.srb.base.consts.SrbMqConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.ExchangeBuilder;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Base64;

@Configuration
@Slf4j
public class MqConfig {

    //确认生产者回调
    @Resource
    RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init(){
        //消息是否到达交换机的回调
        rabbitTemplate.setConfirmCallback((@Nullable CorrelationData var1, boolean var2, @Nullable String var3)->{
            if (!var2){
                //消息未到达交换机
                log.error("消息未到达交换机：{}",var3);
            }
        });

        //消息未到达队列的回调
        rabbitTemplate.setReturnCallback((Message var1, int var2, String var3, String var4, String var5)->{
            //一个消息有 交换机、路由key、消息内容
            log.error("消息未到达队列：replyCode={}, replayText={}, "+
                    "exchange={}, routingKey={}, message={}",var2,var3,var4,var5,new String(Base64.getEncoder().encode(var1.getBody())));
        });

    }

    //配置交换机
    @Bean
    public Exchange smsExchange(){
        return ExchangeBuilder.topicExchange(SrbMqConst.SMS_EXCHANGE)
                .ignoreDeclarationExceptions()
                .durable(true)
                .build();
    }

    @Bean
    public MessageConverter messageConverter(){
        //json字符串转换器
        return new Jackson2JsonMessageConverter();
    }

}
